1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
/*!
Reference types and borrows
*/

use super::*;

/// Reference types
#[derive(Debug, Clone, Eq)]
pub struct Reference {
    /// The referenced type
    ty: ValId,
    /// The constraints values of this reference type must satisfy
    constraints: Constraints,
    /// The free variable set of this reference set
    fv: SymbolSet,
    /// The code of this reference
    code: u64,
}

impl Reference {
    /// Create a new static reference type for a given
    pub fn static_ref(ty: ValId) -> Result<Reference, Error> {
        Self::try_new(ty, &Constraint::default())
    }
    /// Create a new reference with a given type and constraint.
    ///
    /// Return an error if the provided value is not actually a type
    pub fn try_new(ty: ValId, constraint: &Constraint) -> Result<Reference, Error> {
        let mut constraints = ty.elem_constraints()?.clone();
        constraints.rebase_require(Some(ty.clone()), constraint, None, false);
        let mut fv = constraints.fv();
        fv.insert_set(ty.fv());
        let mut result = Reference {
            ty,
            constraints,
            fv,
            code: 0,
        };
        result.fix_code();
        Ok(result)
    }
    /// Get the hasher used for references
    pub fn get_hasher() -> AHasher {
        AHasher::new_with_keys(5452, 1134)
    }
    /// Fix the code of this reference
    fn fix_code(&mut self) {
        let mut hasher = Self::get_hasher();
        self.hash(&mut hasher);
        self.code = hasher.finish()
    }
}

impl PartialEq for Reference {
    fn eq(&self, other: &Reference) -> bool {
        self.ty == other.ty && self.constraints == other.constraints
    }
}

impl Hash for Reference {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.ty.hash(hasher);
        self.constraints.hash(hasher);
    }
}

impl Value for Reference {
    #[inline]
    fn is_ty(&self) -> bool {
        true
    }
    #[inline]
    fn elem_constraints(&self) -> Result<&Constraints, Error> {
        Ok(&self.constraints)
    }
    #[inline]
    fn elem_linearity(&self) -> Result<Linearity, Error> {
        Ok(Linearity::NONLINEAR)
    }
    #[inline]
    fn ty(&self) -> &ValId {
        self.ty.ty()
    }
    fn subtype(&self, other: &ValId, variance: Variance) -> Result<Match, Error> {
        match other.as_enum() {
            ValueEnum::Reference(other) => {
                if self.constraints == other.constraints {
                    self.ty.subtype(&other.ty, variance)
                } else {
                    unimplemented!("General constraint subtyping...")
                }
            }
            _ => Err(Error::TypeMismatch),
        }
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        ValueEnum::Reference(self)
    }
    #[inline]
    fn code(&self) -> u64 {
        self.code
    }
}

/// A borrow of a value
#[derive(Debug, Clone, Eq)]
pub struct Borrowed {
    /// The borrowed value
    borrowed: ValId,
    /// The type of this borrowed value, which is always a reference
    ty: ValId,
    /// The free variable set of this borrowed value
    fv: SymbolSet,
    /// The code of this borrowed value
    code: u64,
}

impl PartialEq for Borrowed {
    fn eq(&self, other: &Borrowed) -> bool {
        self.borrowed == other.borrowed
    }
}

impl Hash for Borrowed {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.borrowed.hash(hasher);
        self.code.hash(hasher);
    }
}

impl Borrowed {
    /// Create a new borrowed value
    pub fn new(borrowed: ValId) -> Borrowed {
        let mut constraint = Constraint::default();
        constraint
            .require(Some(borrowed.clone()), Relationship::EQ, true)
            .expect("Adding a requirement to a null constraint can never fail");
        let ty = Reference::try_new(borrowed.ty().clone(), &constraint)
            .expect("borrowed.ty() is a type")
            .into_valid();
        let fv = borrowed.fv().borrowed_deps();
        let mut result = Borrowed {
            borrowed,
            ty,
            fv,
            code: 0,
        };
        result.fix_code();
        result
    }
    /// Get the hasher used for borrowed values
    pub fn get_hasher() -> AHasher {
        AHasher::new_with_keys(5452, 1354)
    }
    /// Fix the code of this borrowed value
    fn fix_code(&mut self) {
        let mut hasher = Self::get_hasher();
        self.hash(&mut hasher);
        self.code = hasher.finish()
    }
}

impl Value for Borrowed {
    #[inline]
    fn is_ty(&self) -> bool {
        false
    }
    #[inline]
    fn ty(&self) -> &ValId {
        &self.ty
    }
    #[inline]
    fn fv(&self) -> &SymbolSet {
        &self.fv
    }
    #[inline]
    fn into_enum(self) -> ValueEnum {
        ValueEnum::Borrowed(self)
    }
    #[inline]
    fn code(&self) -> u64 {
        self.code
    }
}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn borrowing_constants_yields_static_references() {
        let static_bool = Reference::static_ref(BOOL.clone()).unwrap().into_valid();
        for &b in &[true, false] {
            let bb = Borrowed::new(b.into_valid());
            assert_eq!(*bb.ty(), static_bool)
        }
        let static_nat = Reference::static_ref(NAT.clone()).unwrap().into_valid();
        for n in 0..16 {
            let n = BigUint::new(vec![n]).into_valid();
            let bn = Borrowed::new(n);
            assert_eq!(*bn.ty(), static_nat)
        }
    }
    #[test]
    fn borrow_nat_function() {
        let n = SymbolId::param(NAT.clone()).unwrap();
        let nv = n.clone().into_valid();
        let mut nc = Constraint::new();
        nc.require(Some(nv.clone()), Relationship::EQ, true)
            .unwrap();
        let nb_ref = Reference::try_new(NAT.clone(), &nc).unwrap().into_valid();
        let bn = Borrowed::new(nv).into_valid();
        assert_eq!(*bn.ty(), nb_ref);
        let l = Lambda::try_new(n.clone(), bn).unwrap().into_valid();
        let p = Pi::try_new(
            n,
            nb_ref,
            FunctionalLinearity::new(
                Dependency {
                    variance: Covariant,
                    relationship: Relationship::EQ,
                },
                Linearity::NONLINEAR,
                Usage::OBSERVED,
            ),
        )
        .unwrap()
        .into_valid();
        assert_eq!(*l.ty(), p);
    }
}